package com.yss;

import com.yss.config.ParallelConfig;
import com.yss.config.RouterConfig;
import com.yss.script.ScriptManager;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class RouterMain {

    @Autowired
    private Router router;
    @Autowired
    private Parallel parallel;
    @Autowired
    private RouterConfig routerConfig;
    @Autowired
    private ParallelConfig parallelConfig;

    private ScriptManager scriptManager;

    public RouterMain() {
        scriptManager = new ScriptManager();
    }

    /**
     * 清空所有脚本语句缓存与Klass对象
     */
    public void invalidateAllCache() {
        scriptManager.invalidateCache(CollectionUtils.union(
                routerConfig.getRuleAdaptersMapper().keySet(),
                parallelConfig.getRuleAdaptersMapper().keySet()
        ));
    }


    public List<Object> calculation(Object params) {
        if (params instanceof List) {
            List<Object> paramsList = (List<Object>) params;
            for (Object param : paramsList) {
                return new ArrayList<>(CollectionUtils.union(router.forwarding(param), parallel.forwarding(param)));
            }
        }

        return new ArrayList<>(CollectionUtils.union(router.forwarding(params), parallel.forwarding(params)));
    }

}
